<template>
  <base-page-view class-name="page-container">
    <view class="bg">
      <view v-if="showEmpty" class="emptyBox">
        <image src="/static/images/empty/empty_network.png" />
        <view>没有找到对应的拼团信息</view>
      </view>
      <view v-if="!showEmpty">
        <view class="top">
          <view v-if="baseInfo.picList" class="status">
            <view v-if="needPeople && ifFull" class="done2">拼单已结束</view>
            <view v-if="!needPeople && !ifFull" class="success"><image class="img" src="/static/images/result/gou.png" alt="" />拼单成功</view>
            <view v-if="needPeople" class="time">
              距离拼团结束还剩
              <time-count v-if="timeLeft" style="margin-left: 5px" :time="timeLeft" @timeEnd="endHandle"></time-count>
            </view>
          </view>
          <view class="mention">
            <view v-show="ifFull" class="p">还有更多拼单等着你哦！</view>
            <view v-show="baseInfo.diffPeopleNum <= 0 && !ifFull" class="p">商家正在努力发货，请耐心等待！</view>
          </view>
        </view>
        <view class="userList">
          <view v-if="baseInfo.picList" class="list">
            <!-- 第一个必定显示-->
            <view class="li main">
              <image class="i" src="/static/images/result/fight_master.png" alt="" />
              <image class="img" :src="master" alt="" />
            </view>
            <view class="li ellipsis">
              <view><image class="img" src="/static/images/result/icon_ellipsis.png" alt="" /></view>
            </view>
            <!--剩余人数大于0且未结束的时候显示问号-->
            <view v-if="baseInfo.diffPeopleNum > 0 && !ifFull" class="li wait">
              <image class="img" src="/static/images/result/wait.png" alt="" />
            </view>
            <!--如果成团显示最后一个-->
            <view v-if="baseInfo.diffPeopleNum === 0" class="li">
              <image class="img" :src="baseInfo.picList[baseInfo.picList.length-1]" alt="" />
            </view>
          </view>
          <view v-if="showPeopleNum" class="b">还差{{ baseInfo.diffPeopleNum }}人，赶快邀请好友来拼单吧</view>
        </view>
        <view v-if="baseInfo.diffPeopleNum >= 0" class="opera">
          <view class="btns">
            <view v-if="baseInfo.diffPeopleNum <= 0 && !ifFull" class="span" @click="toList">更多拼单商品</view>
            <view v-if="baseInfo.diffPeopleNum > 0 && timeLeft > 0" class="span" @click="shareClick">
              邀请好友拼单
              <b-open-type open-type="share" :option="shareOption" />
            </view>
            <view v-if="ifFull" class="span" @click="openGroup">我要发起拼单</view>
          </view>
          <view v-show="baseInfo.diffPeopleNum > 0" class="p">分享好友越多，成团越快</view>
        </view>

        <view v-if="adList" class="adList">
          <view v-for="(item, index) in adList" :key="index">
            <image :src="item.pic" :alt="item.title" class="img" mode="widthFix" @click="toAd(item, index)" />
          </view>
        </view>

        <view v-if="groupList" class="other-list">
          <view class="head">
            <image class="img" src="/static/images/result/ele_1.png" alt="" />
            <view class="b">参与拼单</view>
            <image class="img" src="/static/images/result/ele_2.png" alt="" />
          </view>
          <view class="list">
            <view v-for="(item, index) in groupList" :key="index" class="li">
              <view class="info">
                <view class="p user"><image class="img" :src="item.headPic" alt="" /></view>
                <view class="p info">
                  <view class="small">
                    <view class="b">{{ item.headName }}</view>
                  </view>
                  <view class="span">剩余
                    <time-count v-if="item.secondLeft" :time="item.secondLeft"></time-count>
                  </view>
                </view>
              </view>
              <view class="right" @click="returnToBuy(item)">
                <view class="middle">还差<view class="i">{{ item.diffPeopleNum }}</view>人</view>
                <view class="btn">去拼单</view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <confirm-popup ref="confirm" />
    </view>
  </base-page-view>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { toFunctionDetail } from '@/utils/navigateTo'
import TimeCount from '@/components/count-down/bySecond'
import confirmPopup from '@/components/confirmPopup/index'
import { getQueryString } from '@/utils/tools'
import './result.scss'

export default {
  name: 'GroupBuyResult',
  components: {
    TimeCount,
    confirmPopup
  },
  data() {
    return {
      shareOption: {}, // 分享自定义设置
      inviteBtn: null,
      master: null,
      showPeopleNum: false,
      query: {},
      ifFull: '',
      hideNav: false,
      showEmpty: false,
      title: '碧选',
      baseInfo: {},
      adList: [],
      ifTimeEnd: false,
      blankList: [],
      groupList: null,
      timeLeft: 0,
      listQuery: {
        // groupBuyingId: this.$route.query.group_buying_id,
        groupBuyingId: '',
        pageNo: 1,
        pageSize: 10
      },
      second: 0,
      re: 0
    }
  },
  computed: {
    ...mapGetters([
      'goodsTempObj',
      'user'
    ]),
    needPeople() {
      const result = this.baseInfo.diffPeopleNum ? (this.baseInfo.diffPeopleNum > 0) : false
      return result
    }
  },
  onLoad(option) {
    this.shareOption = {}
    this.query = option
    this.ifFull = this.query.group_full
    this.listQuery.groupBuyingId = this.query.group_buying_id
    setTimeout(() => {
      this.askPayResult()
    }, 500)
  },
  onShow() {
    // #ifdef H5
    window.history.pushState({ title: '', url: '#' }, 'title')
    window.addEventListener('popstate', (e) => {
      e.preventDefault()
      this.$router.go(-2)
    }, false)
    // #endif
  },
  onHide() {
    // #ifdef H5
    window.removeEventListener('popstate')
    // #endif
  },
  destroyed() {
    // #ifdef H5
    // 当页面销毁必须要移除这个事件，vue不刷新页面，不移除会重复执行这个事件
    window.removeEventListener('popstate')
    // #endif
  },
  onShareAppMessage(res) {
    if (this.query.order_no) {
      this.$sensorTrack('buttonClick', {
        button_name: '邀请好友拼单',
        button_key: 'group_invite_friend',
        page_name: '开团成功'
      })
    } else {
      this.$sensorTrack('buttonClick', {
        button_name: '邀请好友拼单',
        button_key: 'group_invite_friend',
        page_name: '参团成功'
      })
    }

    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    ...mapActions([
      'setGoodsTemp'
    ]),
    onBrowserBack() {
      this.$navigateTo('/pagesActivity/group-buy/index')
    },
    // 询问支付结果
    askPayResult() {
      if (!this.query.group_full) {
        this.$refs.confirm.show({
          title: '支付结果',
          content: '是否已经支付？',
          yesCb: async() => {
            this.initBaseInfo()
          },
          cancleCb: async() => {
            this.initBaseInfo()
          }
        })
      } else {
        this.initBaseInfo()
      }
    },
    // 发起拼单
    openGroup() {
      const itemInfo = JSON.parse(JSON.parse(uni.getStorageSync('_group_item_info_')).shopping_list)[0]
      // 活动id
      // this.$vux.loading.show({
      //   text: '加载中'
      // })
      itemInfo.group_id = ''
      this.setGoodsTemp({
        shopping_list: JSON.stringify([itemInfo]),
        data: JSON.parse(uni.getStorageSync('_group_item_info_')).data
      })
      this.$navigateTo('/pagesOrder/orderCheck/index')
    },
    // 验证订单是否支付
    async checkPay() {
      // 判断是否付款完成
      const res = await this.$api.orderApi.getOrderDetail({
        order_no: this.query.order_no
      })
      return res.data.status
    },

    // 广告转跳
    toAd(item, index) {
      const obj = {
        page_name: '拼团详情入口',
        key: 'group_buy_ad',
        index: index
      }
      toFunctionDetail(item, this, obj)
    },

    // 倒计时结束的处理
    endHandle() {
      this.initBaseInfo()
    },

    // 去拼团列表
    toList() {
      this.$sensorTrack('buttonClick', {
        button_name: '更多拼单商品',
        button_key: 'group_more_goods'
      })
      this.$navigateTo('/pagesActivity/group-buy/index')
    },

    // 获取基本信息
    async initBaseInfo() {
      // #ifdef MP-WEIXIN
      uni.hideShareMenu()
      // #endif
      const id = this.query.group_id !== '' ? this.query.group_id : ''
      const ONo = this.query.order_no ? this.query.order_no : ''
      // if (!id && !ONo) {
      //   this.showEmpty = true
      //   return
      // }
      // if (id === undefined) {
      //   this.showEmpty = true
      //   return
      // }
      // 如果拼团名额未满(非5000状态)的，则需要检测订单支付状态
      const partFull = this.query.group_full
      if (!partFull && ONo) {
        // 检查是否付款，如果未付款，跳到订单详情
        const payStatus = await this.checkPay()
        if (Number(payStatus) === 1) {
          if (payStatus) {
            this.$navigateTo('/pagesOrder/orderDetail/index?orderNo=' + ONo, '', 'redirectTo')
          }
          return
        }
      }
      const param = { groupId: id, orderNo: ONo, userId: this.user.uid }
      this.$api.promoteApi.getGroupBase(param).then(res => {
        this.baseInfo = res.data
        this.master = res.data.picList[0]
        this.showPeopleNum = (res.data.diffPeopleNum > 0 && res.data.secondLeft > 0)
        // 判断是否有支付结果回调
        if (res.data.secondLeft === -1) {
          setTimeout(this.initBaseInfo, 2500)
          return
        }
        this.timeLeft = res.data.secondLeft
        if (res.data.inviteBtn) {
          this.inviteBtn = res.data.inviteBtn
          this.initShare()
        }
        // 如果还未成团 或者拼团成功
        if ((res.data.diffPeopleNum > 0 && res.data.secondLeft > 0) || res.data.diffPeopleNum <= 0 && !this.ifFull) {
          // #ifdef MP-WEIXIN
          if (res.data.diffPeopleNum > 0 && res.data.secondLeft > 0) {
            uni.showShareMenu()
          }
          // #endif
          // 请求广告
          this.$api.promoteApi.getAdList().then(res => {
            this.adList = res.data
          })
          this.blankList = []
          for (let i = 0; res.data.diffPeopleNum > i; i++) {
            this.blankList.push('1')
          }
        } else if (res.data.diffPeopleNum <= 0 || res.data.secondLeft <= 0) {
          // 如果已经成团 或者时间结束
          this.groupList = res.data.groupHeadVOList
        }
      }).catch(e => {
        uni.showToast({
          title: '网络开了小差查询失败，刷新试试吧~',
          icon: 'none',
          duration: 2 * 1000
        })
      })
    },

    // 分享点击 判断是否微信环境
    shareClick() {
      // #ifdef H5
      if (this.query.order_no) {
        this.$sensorTrack('buttonClick', {
          button_name: '邀请好友拼单',
          button_key: 'group_invite_friend',
          page_name: '开团成功'
        })
      } else {
        this.$sensorTrack('buttonClick', {
          button_name: '邀请好友拼单',
          button_key: 'group_invite_friend',
          page_name: '参团成功'
        })
      }
      // #endif
      // const env = AppUtils.isWechat()
      // if (!env) {
      // const shareUrl = AppUtils.updateInviteCode(this.baseInfo.inviteBtn.url)
      // clip(shareUrl, event)
      // this.$vux.toast.text('链接已复制，去分享给朋友吧')
      // this.$vux.toast.text('请使用浏览器自带的分享按钮进行分享吧')
      // } else {
      // this.$vux.toast.text('点击右上角进行分享操作吧！')
      // }
    },

    //  参与别人的拼单
    async returnToBuy(item) {
      const itemInfo = JSON.parse(JSON.parse(uni.getStorageSync('_group_item_info_')).shopping_list)[0]
      // 活动id
      // this.$vux.loading.show({
      //   text: '加载中'
      // })
      if (typeof (item.groupId) === 'number') {
        itemInfo.group_id = JSON.stringify(item.groupId)
      } else {
        itemInfo.group_id = item.groupId
      }
      this.setGoodsTemp({
        shopping_list: JSON.stringify([itemInfo]),
        data: JSON.parse(uni.getStorageSync('_group_item_info_')).data
      })
      this.$navigateTo('/pagesOrder/orderCheck/index')
      // this.$vux.loading.hide()
      // this.$router.push({
      //   path: '/order/check'
      // })
    },

    // 分享初始化
    initShare() {
      if (this.inviteBtn && this.inviteBtn.url) {
        let share_url = this.inviteBtn.url
        if (share_url.match('/#/')) {
          const urlArr = share_url.split('/#/')
          share_url = urlArr[1].replace('detail/goods', '/pagesDetail/commodity/index')
        } else {
          const url = getQueryString('path', share_url)
          share_url = decodeURIComponent(url)
          // const urlArr = share_url.split('bisinuolan.cn')
          // share_url = urlArr[1]
        }
        this.shareOption.share_title = this.inviteBtn.title
        this.shareOption.share_url = share_url
        this.shareOption.share_icon = this.inviteBtn.pic
        this.shareOption.share_image = this.inviteBtn.pic
        this.shareOption.share_content = this.inviteBtn.content
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
